package org.opsli.modulars.business.appValveWell.web;


import cn.hutool.json.JSONException;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.opsli.api.wrapper.business.patrolStation.PatrolStationModel;
import org.opsli.api.wrapper.system.user.UserModel;
import org.opsli.common.annotation.ApiRestController;
import org.opsli.common.api.Result;
import org.opsli.core.utils.GpsCoordinateUtils;
import org.opsli.core.utils.JiGuangUtil;
import org.opsli.core.utils.JwtUtil;
import org.opsli.core.utils.UserUtil;
import org.opsli.modulars.business.analysisExcel.entity.alsExcel;
import org.opsli.modulars.business.analysisExcel.mapper.ReadExcelMapper;
import org.opsli.modulars.business.analysisExcel.service.IExcelService;
import org.opsli.modulars.business.app.web.CoordinatesConvertUtil;
import org.opsli.modulars.business.app.web.MapCordinatesVo;
import org.opsli.modulars.business.app.web.ZkUtils;
import org.opsli.modulars.business.appValveVersion.entity.AppValveVersion;
import org.opsli.modulars.business.appValveVersion.service.IAppValveVersionService;
import org.opsli.modulars.business.appValveWell.entity.*;
import org.opsli.modulars.business.appValveWell.mapper.AppPatrolStationMapper;
import org.opsli.modulars.business.appValveWell.service.AppTwoValveNowTimeHisService;
import org.opsli.modulars.business.appValveWell.service.AppTwoValveNowTimeService;
import org.opsli.modulars.business.appValveWell.service.AppTwoValveService;
import org.opsli.modulars.business.patrolStation.mapper.PatrolStationMapper;
import org.opsli.modulars.business.patrolStation.service.IPatrolStationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.*;

@Api(tags="app所需接口二类")
@Slf4j
@ApiRestController("/appValves/two")
public class AppTwoValveController {



    @Autowired
    private AppTwoValveService appTwoValveService;
    @Autowired
    private AppTwoValveNowTimeService appTwoValveNowTimeService;
    @Autowired
    private AppPatrolStationMapper appPatrolStationMapper;
    @Autowired
    private IPatrolStationService patrolStationService;
    @Autowired
    private IAppValveVersionService iAppValveVersionService;
    @Autowired
    private AppTwoValveNowTimeHisService appTwoValveNowTimeHisService;
    @Autowired
    private IExcelService iExcelService;
    @Autowired
    private ReadExcelMapper readExcelMapper;
    @Autowired
    private PatrolStationMapper patrolStationMapper;

    public String nameList;
    @Value("${opsli.fileUrl}")
    private  String fileUrl;
    @Value("${opsli.filePath}")
    private  String filePath;


    /**
     * @功能：获取巡点记录
     * @return
     */
    @GetMapping(value = "/alarm")
    public Result<IPage<AppValveDeviceHis>> getAlarm(HttpServletRequest request, AppValveDeviceHis deviceHis,
                                                     @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                     @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                     @RequestParam(name="stationName") String stationName) throws Exception{

        String username = JwtUtil.getUserNameByToken(request);
        UserModel user = UserUtil.getAppUser(username);
        //根据公司id去查阀门井报警信息
        deviceHis.setDevid(user.getCompanyId());
        //根据前端传入的阀门井名称 去查阀门井id
        if(!"".equals(stationName)){
            AppPatrolStation station= appPatrolStationMapper.getFindId(stationName);
            if(null!=station){
                deviceHis.setValveId(station.getId());
            }else {
                deviceHis.setValveId("*");
            }
        }
        Result<IPage<AppValveDeviceHis>> result = new Result<IPage<AppValveDeviceHis>>();
        Page<AppValveDeviceHis> pageList = new Page<AppValveDeviceHis>(pageNo,pageSize);

        pageList = appTwoValveService.getMyList(pageList, deviceHis,(pageNo-1)*pageSize,pageSize);
        List<AppValveDeviceHis> list=pageList.getRecords();
        List<AppValveDeviceHis> hisList=new ArrayList<>();
        for(AppValveDeviceHis model:list){
//            PatrolStationModel stationModel=patrolStationService.get(model.getValveId());
            AppPatrolStation stationModel=appPatrolStationMapper.getId(model.getValveId());
            String lb="";
            if(model.getBit1().equals("1")){ lb+="浓度报警,"; }
            if(model.getBit2().equals("1")){ lb+="水位报警,"; }
            if(model.getBit3().equals("1")){ lb+="门开报警,"; }
            if(model.getBit6().equals("1")){ lb+="移动报警,"; }
            lb = lb.substring(0, lb.length()-1);
            model.setCategory(lb);
            model.setValveName(stationModel.getStationName());//测点名称也是阀门井名称
            hisList.add(model);
        }
        pageList.setRecords(hisList);
        result.setResult(pageList);
        result.setSuccess(true);
        return result;
    }


    /**
     * @功能：阀门井实时数据
     * @return
     */
    @GetMapping(value = "/realTime")
    public Result<IPage<AppValveDeviceNow>> getAlarm(HttpServletRequest request, AppValveDeviceNow deviceNow,
                                                     @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                     @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                     @RequestParam(name="stationName") String stationName) throws Exception{

        String username = JwtUtil.getUserNameByToken(request);
        UserModel user = UserUtil.getAppUser(username);
        //根据公司id去查阀门井报警信息
        deviceNow.setDevid(user.getCompanyId());

        if(!"".equals(stationName)){
            AppPatrolStation station= appPatrolStationMapper.getFindId(stationName);
            if(null!=station){
                deviceNow.setValveId(station.getId());
            }else {
                deviceNow.setValveId("*");
            }
        }
        Result<IPage<AppValveDeviceNow>> result = new Result<IPage<AppValveDeviceNow>>();
        Page<AppValveDeviceNow> pageList = new Page<AppValveDeviceNow>(pageNo,pageSize);

        pageList = appTwoValveNowTimeService.getMyList(pageList, deviceNow,(pageNo-1)*pageSize,pageSize);
        List<AppValveDeviceNow> list=pageList.getRecords();
        List<AppValveDeviceNow> hisList=new ArrayList<>();
        for(AppValveDeviceNow model:list){
//            PatrolStationModel stationModel=patrolStationService.get(model.getValveId());
            AppPatrolStation stationModel=appPatrolStationMapper.getId(model.getValveId());

            model.setValveName(stationModel.getStationName());//测点名称也是阀门井名称
            String flag=null;
         /*   if(model.getBit0().equals("0") && model.getBit1().equals("0") && model.getBit2().equals("0")
                    && model.getBit3().equals("0") && model.getBit4().equals("0") && model.getBit5().equals("0")
                    && model.getBit6().equals("0") && model.getBit7().equals("0") && model.getBit8().equals("0")){*/
            if(model.getBit1().equals("0") && model.getBit2().equals("0")
                    && model.getBit3().equals("0")&& model.getBit6().equals("0")){
                flag="0";
            }else {
                flag="1";
            }
            model.setSiren(flag);
            hisList.add(model);
        }
        pageList.setRecords(hisList);
        result.setResult(pageList);
        result.setSuccess(true);
/*        JiGuangUtil j=new JiGuangUtil();
        System.out.println("-----------------------"+user.getId());
        j.pushAline(user.getId(),"您所负责的阀门井发生浓度超标报警","创源智能");*/
        return result;
    }

    /**
     * @功能：阀门井实时数据
     * @return
     */
    @GetMapping(value = "/dalianRealTime")
    public Result<IPage<AppValveDeviceNow>> getDalianRealTime(HttpServletRequest request, AppValveDeviceNow deviceNow,
                                                     @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                     @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                     @RequestParam(name="deviceId") String deviceId) throws Exception{

        String username = JwtUtil.getUserNameByToken(request);
        UserModel user = UserUtil.getAppUser(username);
        //根据公司id去查阀门井报警信息
        deviceNow.setDevid(user.getCompanyId());

        deviceNow.setDeviceId(deviceId);
        Result<IPage<AppValveDeviceNow>> result = new Result<IPage<AppValveDeviceNow>>();
        Page<AppValveDeviceNow> pageList = new Page<AppValveDeviceNow>(pageNo,pageSize);

        pageList = appTwoValveNowTimeService.getMyListDaLian(pageList, deviceNow,(pageNo-1)*pageSize,pageSize);

        List<AppValveDeviceNow> list=pageList.getRecords();
        List<AppValveDeviceNow> hisList=new ArrayList<>();
        for(AppValveDeviceNow model:list){
//            PatrolStationModel stationModel=patrolStationService.get(model.getValveId());

            String flag=null;
         /*   if(model.getBit0().equals("0") && model.getBit1().equals("0") && model.getBit2().equals("0")
                    && model.getBit3().equals("0") && model.getBit4().equals("0") && model.getBit5().equals("0")
                    && model.getBit6().equals("0") && model.getBit7().equals("0") && model.getBit8().equals("0")){*/
            if(model.getBit1().equals("0") && model.getBit2().equals("0")
                    && model.getBit3().equals("0")&& model.getBit6().equals("0")){
                flag="0";
            }else {
                flag="1";
            }
            model.setSiren(flag);
            hisList.add(model);
        }
        pageList.setRecords(hisList);
        result.setResult(pageList);
        result.setSuccess(true);
/*        JiGuangUtil j=new JiGuangUtil();
        System.out.println("-----------------------"+user.getId());
        j.pushAline(user.getId(),"您所负责的阀门井发生浓度超标报警","创源智能");*/
        return result;
    }

    /**
     * @功能：阀门井实时数据
     * @return
     */
    @GetMapping(value = "/dlJinZhouValue")
    public Result<IPage<AppValveStation>> dlJinZhouValue(HttpServletRequest request,
                                                         @RequestParam(name="msgCategory") String msgCategory,
                                                         @RequestParam(name="valveName") String valveName,
                                                         @RequestParam(name="deviceId") String deviceId,
                                                         @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                         @RequestParam(name="pageSize", defaultValue="10") Integer pageSize
                                                         ) throws Exception{

        String valveNames = URLEncoder.encode(valveName, "utf-8");  //输出%C4%E3%BA%C3
        String deviceIds = URLEncoder.encode(deviceId, "utf-8");  //输出%C4%E3%BA%C3

        //发送 GET 请求，第一个参数为url，第二个参数为请求参数
        String s=sendGet("http://101.200.55.121:8098//system/station/dlJinZhouValue", "msgCategory="+msgCategory+"&valveName="+valveNames+"&deviceId="+deviceIds+"&pageNo="+pageNo+"&pageSize="+pageSize+"");

        List<AppValveStation> list = new ArrayList<AppValveStation>();
        list = JSONObject.parseArray(s, AppValveStation.class);

        for (AppValveStation station:list){
            //       高德火星坐标系 WGS84转
            double[] gpsCoUtils= GpsCoordinateUtils.calGCJ02toWGS84(Double.parseDouble(station.getDimension()),Double.parseDouble(station.getLongitude()));
            Double n = gpsCoUtils[0];//经度
            Double l = gpsCoUtils[1];//维度
            station.setMkln(l);
            station.setMklo(n);
        }
        String username = JwtUtil.getUserNameByToken(request);
        UserModel user = UserUtil.getAppUser(username);

        Result<IPage<AppValveStation>> result = new Result<IPage<AppValveStation>>();
        Page<AppValveStation> pageList = new Page<AppValveStation>(pageNo,pageSize);
        pageList.setRecords(list);

        result.setResult(pageList);
        result.setSuccess(true);

        return result;
    }

    /**
     * @功能：阀门井实时历史数据
     * @return
     */
    @GetMapping(value = "/realTimeHis")
    public Result<IPage<AppValveDeviceNowHis>> getAlarmHis(HttpServletRequest request, AppValveDeviceNowHis deviceNowHis,
                                                           @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                           @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                           @RequestParam(name="stationName") String stationName) throws Exception{

        String username = JwtUtil.getUserNameByToken(request);
        UserModel user = UserUtil.getAppUser(username);
        //根据公司id去查阀门井报警信息
        deviceNowHis.setDevid(user.getCompanyId());

        if(!"".equals(stationName)){
            AppPatrolStation station= appPatrolStationMapper.getFindId(stationName);
            if(null!=station){
                deviceNowHis.setValveId(station.getId());
            }else {
                deviceNowHis.setValveId("*");
            }
        }
        Result<IPage<AppValveDeviceNowHis>> result = new Result<IPage<AppValveDeviceNowHis>>();
        Page<AppValveDeviceNowHis> pageList = new Page<AppValveDeviceNowHis>(pageNo,pageSize);

        pageList = appTwoValveNowTimeHisService.getMyList(pageList, deviceNowHis,(pageNo-1)*pageSize,pageSize);
        List<AppValveDeviceNowHis> list=pageList.getRecords();
        List<AppValveDeviceNowHis> hisList=new ArrayList<>();
        for(AppValveDeviceNowHis model:list){
            AppPatrolStation stationModel=appPatrolStationMapper.getId(model.getValveId());

            model.setValveName(stationModel.getStationName());//测点名称也是阀门井名称
            String flag=null;
            if(model.getBit1().equals("0") && model.getBit2().equals("0")
                    && model.getBit3().equals("0")&& model.getBit6().equals("0")){
                flag="0";
            }else {
                flag="1";
            }
            model.setSiren(flag);
            hisList.add(model);
        }
        pageList.setRecords(hisList);
        result.setResult(pageList);
        result.setSuccess(true);
        return result;
    }

    @GetMapping(value = "/getUserInfo")
    public Result<Map> getUserInfo(HttpServletRequest request) throws Exception{
        String username = JwtUtil.getUserNameByToken(request);
        Result<Map> result=new Result<Map>();
        UserModel user = UserUtil.getAppUser(username);
        Map map=new HashMap();
        map.put("sign",user.getIsInspector());
        result.setSuccess(true);
        result.setResult(map);
        return result;
    }

    @RequestMapping(value = "/getUser", method = RequestMethod.GET)
    public Map getUser(HttpServletRequest request) throws Exception{
        String username = JwtUtil.getUserNameByToken(request);
        UserModel user = UserUtil.getAppUser(username);
        Map map=new HashMap();
        map.put("userId",user.getId());
        return map;
    }


    @RequestMapping(value = "/jiguang",method = RequestMethod.GET)
    public Result getUjiguang(HttpServletRequest request, @RequestParam(name="id") String id,
                                                            @RequestParam(name="alert") String alert) throws Exception{
        Result result = new Result();
        JiGuangUtil j=new JiGuangUtil();
        System.out.println("-----------------------"+id);
        j.pushAline(id,alert,"创源智能");
        Map map=new HashMap();

        map.put("userId",id);
        result.setSuccess(true);
        return result;
    }

    @GetMapping(value = "/upgrade")
    public Result<Map> upgrade(HttpServletRequest request, @RequestParam(name="appid") String appid, @RequestParam(name="version") String version,@RequestParam(name="imei") String imei) throws Exception{

        System.out.println("appid="+appid+",version="+version+",imei="+imei);
        Result<Map> result=new Result<Map>();
        AppValveVersion  appValveVersion=iAppValveVersionService.findLast();
        Map map=new HashMap();
        map.put("version",appValveVersion.getAppVersion());
        map.put("note",appValveVersion.getNote());
        map.put("url",appValveVersion.getUrl());
        result.setSuccess(true);
        result.setResult(map);
        return result;
    }

    @RequestMapping(value = "/excel",method = RequestMethod.GET)
    public Result getExcel(HttpServletRequest request)throws Exception{
        Result result = new Result();
        String fullFileName = "C:\\Users\\HY\\Downloads\\调压设备.xlsx";
        InputStream is = new FileInputStream(fullFileName);
        List<alsExcel> list = new ArrayList<>();
        XSSFWorkbook xWorkbook = new XSSFWorkbook(is);
        // Read the Sheet
        XSSFSheet xssfSheet = xWorkbook.getSheetAt(0);

        // Read the Row
        for (int rowNum = 2; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
            XSSFRow xssfRow = xssfSheet.getRow(rowNum);
            if (xssfRow != null) {
                alsExcel order =new alsExcel();
                // 单元格从 0 开始
                order.setDevid("41001");
                String name=xssfRow.getCell(1).getStringCellValue();
                if(!name.equals("")){
                    order.setHousingName(name);
                    nameList=name;
                }else {
                    order.setHousingName(nameList);
                }
                order.setLocation(xssfRow.getCell(2).getStringCellValue());
                order.setConditions(xssfRow.getCell(3).getStringCellValue());
                iExcelService.insertUser(order);
                list.add(order);

            }

        }
        xWorkbook.close();;
        System.out.println("size==>" + list.size());
        for (alsExcel list1:list){
            System.out.println(list1.getDevid()+"---"+list1.getHousingName()+"---"+list1.getLocation()+"---"+list1.getConditions());
        }
        result.setSuccess(true);
        return result;
    }

    /**
     * 调压箱列表信息
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/pressure",method = RequestMethod.GET)
    public Result getPressure(HttpServletRequest request,String devid)throws Exception {
        List<PatrolStationModel> models =patrolStationService.findListByType(devid,"4");

        Map<String,Integer> mapsName = new HashMap<>();
        for(PatrolStationModel str:models){
            Integer i = 1; //定义一个计数器，用来记录重复数据的个数
            if(mapsName.get(str.getVillageName()) != null){
                i=mapsName.get(str.getVillageName())+1;
            }
            mapsName.put(str.getVillageName(),i);
        }
        List<alsExcel> list=new ArrayList<>();
        for (Map.Entry<String, Integer> entry : mapsName.entrySet()) {
            String mapKey = entry.getKey();
            Integer mapValue = entry.getValue();
            alsExcel alsExcel=new alsExcel();
            alsExcel.setHousingName(mapKey);
            alsExcel.setConditions(mapValue.toString());
            list.add(alsExcel);
        }

        Result result = new Result();
        List<Map> maps=new ArrayList<>();
            for (alsExcel model : list) {
                Map map = new HashMap();
                    map.put("housingName", model.getHousingName());
                    map.put("conditions", model.getConditions());//当前小区下的调压箱个数
                    if(!model.getHousingName().equals("")) {
                        maps.add(map);
                    }
                }
        result.setResult(maps);
        result.setSuccess(true);
        return result;
    }

    /**
     * 调压柜列表信息
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/cabinet",method = RequestMethod.GET)
    public Result getCabinet(HttpServletRequest request,String devid)throws Exception {
        Result result = new Result();
        List<PatrolStationModel> list= patrolStationMapper.getCabinetList(devid);
        List<Map> maps=new ArrayList<>();
        for (PatrolStationModel model : list) {
            Map map = new HashMap();
            map.put("stationName",model.getStationName());//调压柜名称
            map.put("id",model.getId());//训点id
            maps.add(map);
        }
        result.setResult(maps);
        result.setSuccess(true);
        return result;
    }

    /**
     * 调压柜地图信息
     * @param request
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/dpCabinet")
    public List<Map> dpCabinet(HttpServletRequest request,String devid) throws Exception{
        Map datamap=new HashMap();
        List<Map> list=new ArrayList<Map>();
        List<PatrolStationModel> models =patrolStationService.findListByType(devid,"3");
        if(models!=null&&models.size()>0){
            for(PatrolStationModel model:models){
                Map map=new HashMap();
                map.put("name",model.getStationName());
                map.put("id",model.getId());
                map.put("type","121");
                MapCordinatesVo cordinatesVo=new MapCordinatesVo();
                if(ZkUtils.isNotBlank(model.getLongitude())) {
                    cordinatesVo.setLon(new BigDecimal(model.getLongitude()));
                    cordinatesVo.setLat(new BigDecimal(model.getDimension()));
                    cordinatesVo = CoordinatesConvertUtil.bd_encrypt(cordinatesVo);
                    map.put("ln", cordinatesVo.getLon());
                    map.put("lt", cordinatesVo.getLat());
                    map.put("location", model.getLocation());
                    map.put("userName", model.getUserName());
                    map.put("lastTime", model.getLastTime());
                    map.put("pic", fileUrl+model.getLastPic());
                    map.put("video", fileUrl+model.getLastVideo());
                    list.add(map);
                }
            }
        }
        return list;
    }

    /**
     * 调压箱子地图信息
     * @param request
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/dphest")
    public List<Map> dphest(HttpServletRequest request,String devid) throws Exception{
        Map datamap=new HashMap();
        List<Map> list=new ArrayList<Map>();
        List<PatrolStationModel> models =patrolStationService.findListByType(devid,"4");

        Map<String,Integer> maps = new HashMap<>();
        for(PatrolStationModel str:models){
            Integer i = 1; //定义一个计数器，用来记录重复数据的个数
            if(maps.get(str.getVillageName()) != null){
                i=maps.get(str.getVillageName())+1;
            }
            maps.put(str.getVillageName(),i);
        }
        System.out.println("重复数据的个数："+maps.toString());
        List<PatrolStationModel> mo=new ArrayList<>();
        for (String key : maps.keySet()) {
            List<PatrolStationModel> listName =patrolStationMapper.findListByTypeName(devid,"4",key);
            for (int i=0;i==0;i++){
                mo.add(listName.get(i));
            }
            System.out.println(key);
        }




        if(mo!=null&&mo.size()>0){
            for(PatrolStationModel model:mo){

                Map map=new HashMap();
                map.put("name",model.getVillageName());//调压箱小区名称
                map.put("id",model.getId());
                map.put("type","121");
                MapCordinatesVo cordinatesVo=new MapCordinatesVo();
                if(ZkUtils.isNotBlank(model.getLongitude())) {
                    try {
                        cordinatesVo.setLon(new BigDecimal(model.getLongitude()));
                        cordinatesVo.setLat(new BigDecimal(model.getDimension()));
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                    cordinatesVo = CoordinatesConvertUtil.bd_encrypt(cordinatesVo);
                    map.put("ln", cordinatesVo.getLon());
                    map.put("lt", cordinatesVo.getLat());
                    map.put("location", model.getLocation());
                    map.put("userName", model.getUserName());
                    map.put("lastTime", model.getLastTime());
                    list.add(map);
                }
            }
        }

        return list;
    }

    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);

            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();

            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            connection.setRequestProperty("Charsert", "UTF-8");
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");


            // 建立实际的连接
            connection.connect();

            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();

            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }

            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }

        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url：发送请求的 URL
     * @param param：请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return String[result]：所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);

            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();

            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);

            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());

            // 发送请求参数
            out.print(param);

            // flush输出流的缓冲
            out.flush();

            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }

        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }


}
